import { Table, Row, Col, Button, Modal, Form, Input, Select, message, Space, Popconfirm } from 'antd';
import { getUser, addUser, updateUser, deleteUser } from '@/services/user';
import { useRequest } from '@umijs/max';
import { PageContainer } from '@ant-design/pro-components';
import { useState } from 'react';
import ConfigForm from '@/components/ConfigForm';
import { ExclamationCircleFilled, SearchOutlined } from '@ant-design/icons'
import fields from './fields';
function Users() {
    //Instance created by `useForm` is not connected to any Form element. Forget to pass `form` prop?
    const [form] = Form.useForm();//创建 Form 实例，用于管理所有数据状态。
    const [userModalVisible, setUserModalVisible] = useState(false);
    const [currentRecord, setCurrentRecord] = useState(null);//存放当前正在编辑的用户
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [selectedRows, setSelectedRows] = useState([]);
    const [searchUsername, setSearchUsername] = useState('');//搜索用户名
    const [searchEmail, setSearchEmail] = useState('');//搜索的邮箱
    const [searchPhone, setSearchPhone] = useState('');//搜索用的手机号
    const [currentPagination, setCurrentPagination] = useState({current:1,pageSize:20});
    const getUserRequest = useRequest(async function (pagination=currentPagination) {
        let params: any = {pageNum:pagination.current,pageSize:pagination.pageSize};
        setCurrentPagination(pagination);
        if (searchUsername) {
            params.username = searchUsername;
        }
        if (searchEmail) {
            params.email = searchEmail;
        }
        if (searchPhone) {
            params.phone = searchPhone;
        }
        return getUser(params);
    });
    const updateUserRequest = useRequest(updateUser, {
        manual: true,
        onSuccess() {//更新后的回调
            message.success('更新用户成功');
            getUserRequest.refresh();//刷新用户列表
            setUserModalVisible(false);//关掉模态窗口
        },
        onError() {//更新用户失败的回调
            message.error('更新用户失败');//提示用户添加失败
        }
    });
    const addUserRequest = useRequest(addUser, {//添加用户
        manual: true,//手工调用
        onSuccess() {//成功后的回调
            message.success('新增用户成功');
            getUserRequest.refresh();//刷新用户列表
            setUserModalVisible(false);//关掉模态窗口
        },
        onError() {//添加用户失败的回调
            message.error('新增用户失败');//提示用户添加失败
        }
    });
    const deleteUserRequest = useRequest(deleteUser, {//添加用户
        manual: true,//手工调用
        onSuccess() {//成功后的回调
            message.success('删除用户成功');
            getUserRequest.refresh();//刷新用户列表
        },
        onError() {//添加用户失败的回调
            message.error('删除用户失败');//提示用户添加失败
        }
    });
    const handleSaveUser = async () => {
        const values = await form.validateFields();//校验用户输入是否正确
        if (currentRecord) {//如果currentRecord有值，说明是编辑或者说更新
            updateUserRequest.run(currentRecord.id, values);//如果正确 的话可以调用接口添加用户
        } else {
            addUserRequest.run(values);//如果正确 的话可以调用接口添加用户
        }
    }
    const handleDeleteUser = (id) => {
        deleteUserRequest.run(id);
    }
    const batchDeleteUsers = () => {
        if(selectedRows.length>0){
            Modal.confirm({
                title: '你是否想删除这些用户?',
                icon: <ExclamationCircleFilled />,
                content: selectedRows.map(row => row.username).join(','),
                onOk() {
                    //把选中的行的key的数组，也就是每个用户对象的ID数组传给run方法进行删除
                    deleteUserRequest.run(selectedRowKeys);
                }
            });
        }else{
            message.warn('请至少选择一条数据');
        }
    }
    const columns = [
        { title: 'ID', dataIndex: 'id' },
        { title: '用户名', dataIndex: 'username' },
        { title: '邮箱', dataIndex: 'email' },
        { title: '手机号', dataIndex: 'phone' },
        {
            title: '性别', dataIndex: 'gender', render: (gender) => {
                return gender === 1 ? '男' : '女';
            }
        },
        {
            title: '角色', dataIndex: 'access', render: (access) => {
                switch (access) {
                    case 'root':
                        return '超级管理员';
                    case 'admin':
                        return '管理员';
                    default:
                        return '普通会员'
                }
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_, record) => (
                <Space size="small">
                    <a onClick={() => showUserModal(record)} >编辑</a>
                    <Popconfirm title="确定要删除吗?" onConfirm={() => handleDeleteUser(record.id)}>
                        <a style={{ color: 'red' }}>删除</a>
                    </Popconfirm>
                </Space>
            )
        }
    ]
    const showUserModal = (record) => {
        form.resetFields();
        setCurrentRecord(record);//设置当前正在编辑的用户
        if (record) {
            form.setFieldsValue(record);
        }
        setUserModalVisible(true);
    }
    const rowSelection = {
        selectedRowKeys,//指定哪些行被选中了，这是行的ID的数组
        onChange(selectedRowKeys, selectedRows) {//当选中项改变的时候执行的回调
            setSelectedRowKeys(selectedRowKeys);
            setSelectedRows(selectedRows);
        }
    }
    const handleSearch = () => {
        getUserRequest.run({...currentPagination,current:1});
    }
    return (
        <PageContainer>
            <Row>
                <Col flex="auto">
                    <Input
                        placeholder='用户名'
                        value={searchUsername}
                        onChange={event => setSearchUsername(event.target.value)}
                        style={{ width: '120px', marginRight: '16px' }} />
                    <Input
                        placeholder='邮箱'
                        value={searchEmail}
                        onChange={event => setSearchEmail(event.target.value)}
                        style={{ width: '120px', marginRight: '16px' }} />
                    <Input
                        placeholder='手机号'
                        value={searchPhone}
                        onChange={event => setSearchPhone(event.target.value)}
                        style={{ width: '120px', marginRight: '16px' }} />
                    <Button
                        type="primary"
                        shape="circle"
                        icon={<SearchOutlined />}
                        onClick={handleSearch} />
                </Col>
                <Col flex="none">
                    <Space>
                        <Button type="primary" onClick={() => showUserModal(null)}>新增用户</Button>
                        <Button disabled={selectedRows.length<=0} type="primary" danger onClick={batchDeleteUsers}>全部删除</Button>
                    </Space>
                </Col>
            </Row>
            <Table
                rowKey="id"
                columns={columns}
                dataSource={getUserRequest.data?.list || []}
                loading={getUserRequest.loading}
                rowSelection={rowSelection}
                pagination={{
                    ...currentPagination,//current,pageSize
                    position:['bottomCenter'],//指定分页器的位置 
                    pageSizeOptions:[2,10, 20, 50, 100],//指定每页可以显示多少条的枚举
                    showQuickJumper:true,//是不显示快速跳转输入框
                    showSizeChanger:true,//是否展示 pageSize 切换器，当 total 大于 50 时默认为 true
                    total:getUserRequest.data?.total,//总条数
                    showTotal:(total, range) => `${total}条中的${range[0]}-${range[1]}条`,
                    //当切换码页的时候或者改变 每页显示条数的时候会执行此函数
                    onChange:(current, pageSize)=>{
                        let pagination = {current, pageSize};
                        getUserRequest.run(pagination);
                    }//页码或 pageSize 改变的回调，参数是改变后的页码及每页条数
                }}
            />
            <Modal
                title={"新增用户"}
                open={userModalVisible}
                onCancel={() => setUserModalVisible(false)}
                onOk={handleSaveUser}
            >
                <ConfigForm
                    fields={fields}
                    form={form}
                />
            </Modal>
        </PageContainer>
    )
}
export default Users;